<template>
	<scroll-view scroll-y class="scroll-view-content" type="list">
		<div class="orderDetails" :style="{ paddingBottom: utils.windowBottom + 80 + 'px' }">
			<div>
				<div class="flex" style="justify-content: space-between;margin-bottom: 20rpx;">
					<div style="font-weight: 500;">仓库</div>
					<div style="color: #666;">{{opt && opt['仓库名称'] && opt['仓库名称'] != 'null'? opt['仓库名称']  : ''}}</div>
				</div>
				<div class="flex" style="justify-content: space-between;margin-bottom: 20rpx;">
					<div>仓位编号</div>
					<div style="color: #666;">{{opt && opt['仓位编号'] && opt['仓位编号'] != 'null'? opt['仓位编号'] : ''}}</div>
				</div>
				<div class="flex" style="justify-content: space-between;">
					<div>货主</div>
					<div style="color: #666;">{{opt && opt['客户名称'] && opt['客户名称'] != 'null'? opt['客户名称'] : ''}}</div>
				</div>
			</div>
			<template v-if="list && list.length > 0">
				<div class="orderData" v-for="(detailedItem, detailedIndex) in list" :key="detailedIndex">
					<template v-for="(item, index) in detailedItem" :key="index">

						<div class="formItem" :class="item?.type == 5 || item?.type == 6 ? '' : 'flexCenter'"
							:style="{ borderBottom: item.type == 5 ? '0' : '1px solid #ccc' }" v-if="item.isShow">
							<div
								style="display: flex;align-items: center;justify-content: space-between;white-space: nowrap">
								<div style="color:#666"><span class="required" v-if="item.required">*</span>{{ item.title }}</div>
							</div>
							<div style="font-size: 32rpx; display: flex; align-items: center;margin-left: 20rpx;text-align: right;"
								v-if="item.type == 3">
								{{ item.value }}
							</div>
							<div style="color: #3975f6;text-align: right;"
								@click.stop="showSelectPop(item,detailedIndex)" v-else-if="item.type == 2">
								{{item.value || '选择' }}
							</div>
							<input v-else-if="item.type == 1" class="value" :type="'text'" v-model="item.value"
								placeholder="请输入" style="text-align: right; color: #3975f6" />

							<checkbox v-else-if="item.type == 4" :checked="item.value"
								@click.stop="item.value = !item.value" />

							<textarea v-else-if="item.type == 5" style="
				    padding: 20rpx;
				    border: 1px solid #ccc;
				    height: 200rpx;
				    width: 100%;
				    margin-top: 20rpx;
				    box-sizing: border-box;
				  " v-model="item.value" placeholder="请输入" placeholder-style="font-weight: 400; color: #999;"></textarea>

						</div>

					</template>
					<div class="flex" style="justify-content: flex-end; padding: 0; margin-top: 30rpx">
						<van-button type="danger" size="small" @click="deleteMaterial(detailedIndex)">删除</van-button>
					</div>
				</div>
			</template>

			<!-- 	<template v-if="list && list.length > 0">
				<div class="orderData" v-for="(item, index) in list" :key="index">

					<div class="flexCenter formItem">
						<div>物料编号</div>
						<div style="color: #3975f6" @click.stop="showSelectPop(index,'物料')">
							{{item?.FNumber?.value? item?.FNumber?.value: '选择'}}
						</div>
					</div>

					<div class="flexCenter item">
						<div><span class="required">*</span>数量</div>
						<input class="value" type="digit" v-model="item.qty.value" placeholder="请输入"
							style="text-align: right; color: #3975f6" />
					</div>
					<template v-if="opt && opt?.parentPage == '出库单'|| opt?.parentPage == '调拨单'">
						<view>
							<div class="flexCenter item">
								<div><span class="required">*</span>批号</div>
								<div class="value" @click="showSelectPop(index,'批号')">{{item.FLot.value || '选择' }}</div>
							</div>
						</view>
						<template v-if="opt?.parentPage == '调拨单'">
							<view>
								<div class="flexCenter item">
									<div><span class="required">*</span>调入仓库</div>
									<div class="value">{{item.FDestStockId.value || '' }}</div>
								</div>
								<div class="flexCenter item">
									<div><span class="required">*</span>调入仓位</div>
									<div class="value" @click="showSelectPop(index,'调入仓位')">
										{{item.FDestStockLocId.value || '选择' }}
									</div>
								</div>
							</view>
						</template>
					</template>
					<template v-else>
						<div class="flexCenter item">
							<div><span class="required">*</span>费用项</div>
							<div class="value" @click="showSelectPop(index,'费用项目')">{{item.feeItem.value || '选择' }}
							</div>
						</div>
			
						<div class="flexCenter item">
							<div><span class="required">*</span>计费标准</div>
							<div class="value" @click="showSelectPop(index,'计费标准')">{{item.feeStandard.value || '选择' }}
							</div>
						</div>
						<div class="flexCenter item">
							<div><span class="required">*</span>食用到期日</div>
							<div class="value"
								@click="popType = '食用到期日',isShowDateTime = true,currentSelectIndex = index">
								{{item.expiryDate.value || '选择' }}
							</div>
						</div>
						<div class="flexCenter item">
							<div><span class="required">*</span>生产日期</div>
							<div class="value"
								@click="popType = '生产日期',isShowDateTime = true,currentSelectIndex = index">
								{{item.FProduceDate.value || '选择' }}
							</div>
						</div>
						<div class="flexCenter item">
							<div><span class="required">*</span>有效期至</div>
							<div class="value"
								@click="popType = '有效期至',isShowDateTime = true,currentSelectIndex = index">
								{{item.FExpiryDate.value || '选择' }}
							</div>
						</div>
					</template>

					<template v-for="(v, i) in item" :key="i">
						<div class="orderDataItem flex" v-if="v.isShow">
							<div class="key">{{ v.title }}</div>
							<div class="value" style="word-break: break-all">
								{{ v.value }}
							</div>
						</div>
					</template>
					<div class="flex" style="justify-content: flex-end; padding: 0; margin-top: 30rpx">
						<van-button type="danger" size="small" @click="deleteMaterial(index)">删除</van-button>
					</div>
				</div>
			</template> -->
		</div>
	</scroll-view>
	<div class="btns" :style="{ paddingBottom: utils.windowBottom + 10 + 'px' }">
		<div @click.stop="save">{{ '保存' }}</div>
	</div>
	<div class="add">
		<img src="/static/image/addIcon.png" alt="" @click="addMaterial" style="margin-bottom: 20rpx;" />
		<img src="/static/image/scan.png" alt="" @click="addByScan"
			:style="{ paddingBottom: utils.windowBottom + 'px' }" />
	</div>

	<selectCom :type="popType" :show="isShowPop" @close="close" @submit="popSubmit" :filterList="filterList"
		:FieldKeys="popFieldKeys" :FilterString="filterString" :FormId="popFormId" :isAddFUseOrgId="isAddFUseOrgId">
	</selectCom>
	<selectDateTime :show="isShowDateTime" @close="isShowDateTime = false" @submit="selectDateTimeFn"></selectDateTime>
	<van-action-sheet :show="isShowSelectAssistantMethod" :actions="assistantList"
		@close="isShowSelectAssistantMethod = false" @select="selectAssistantMethod" cancel-text="取消" />
</template>

<script setup lang="ts">
	import utils from '@/utils';
	import selectCom from '@/components/selectCom.vue';
	import selectDateTime from '@/components/selectDateTime.vue';
	import { compile, computed, ref, watch } from 'vue';
	import { onLoad, onShow } from '@dcloudio/uni-app';
	import { useStore } from 'vuex';
	import {
		getAllocateMaterial,
		getOrderDetailByBillNo,
		getOrderList,
	} from '@/api/user';
	import { Utils } from '@/utils/utils';
	const { getters, commit } = useStore();
	// 选择弹窗type
	const popType = ref('')
	// 当前编辑的数据index
	const currentSelectIndex = ref(0)
	// 是否显示时间选择
	const isShowDateTime = ref(false)
	/**
	 * type 1 输入 2 选择 3 不能操作 4 开关 5 多行输入 6 图片上传
	 */
	const dataDetail = ref({


		// 物料编号
		FNumber: {
			title: '物料编号',
			number: '',
			value: '',
			isShow: true,
			type: 3
		},
		// 物料名称
		FName: {
			title: '物料名称',
			number: '',
			value: '',
			isShow: true,
			type: 3
		},

		// 单位
		Unit: {
			title: '单位',
			number: '',
			value: '',
			isShow: true,
			type: 3
		},

		// 数量
		qty: {
			title: '数量',
			value: '',
			isShow: true,
			required: true,
			type: 1
		},
		// 费用项目
		feeItem: {
			title: '费用项目',
			value: '',
			number: '',
			isShow: false,
			type: 2,
		},
		// 计费标准
		feeStandard: {
			title: '计费标准',
			value: '',
			number: '',
			isShow: false,
			type: 2,
		},
		FDestStockId: {
			title: '调入仓库',
			value: '',
			number: '',
			isShow: false,
			type: 3,
		},
		FDestStockLocId: {
			title: '调入仓位',
			value: '',
			number: '',
			// 仓位集id
			id: '',
			isShow: false,
			type: 2,
		},

		// 批号
		FLot: {
			title: '批号',
			value: '',
			isShow: false,
			type: 2,
		},
		FProduceDate: {
			title: '生产日期',
			value: '',
			isShow: false,
			type: 2,
		},
		FExpiryDate: {
			title: '有效期至',
			value: '',
			isShow: false,
			type: 2,
		},
		// 食用到期日
		expiryDate: {
			title: '食用到期日',
			value: '',
			isShow: false,
			type: 2,
		},

		// 计费方式
		// feeType: {
		// 	title: '计费方式',
		// 	number: '',
		// 	value: '',
		// 	isShow: false,
		// 	type: 2,
		// },

	});
	const list = ref([] as any);
	// 显示选择弹窗
	const isShowPop = ref(false);
	// 弹窗查询字段
	const popFieldKeys = ref('')
	// 弹窗formid
	const popFormId = ref('')
	// 弹窗过滤列表
	const filterList = ref([] as any)
	// 过滤字段集合
	const filterString = ref([] as any)
	// 是否添加组织过滤条件
	const isAddFUseOrgId = ref(true)
	// 点击选择
	const showSelectPop = async (item : any, index : number) => {
		const type = item.title;
		popFieldKeys.value = ''
		isAddFUseOrgId.value = true;
		currentSelectIndex.value = index
		filterString.value = []
		filterList.value = []
		popType.value = type
		// 日期选择
		if (item.title == '食用到期日' || item.title == '日期' || item.title == '收货日期' || item.title == '有效期至' || item.title == '生产日期') {
			isShowDateTime.value = true
			return
		}
		if (type == '计费方式' || type == '计费标准') {
			// getAssistantInfo('RKDJFFS')
			assistantList.value = await Utils.getAssistantInfo(type == '计费标准' ? '001' : 'RKDJFFS')
			isShowSelectAssistantMethod.value = true
		} else {
			if (type == '费用项目') {
				popFieldKeys.value = "FNumber,FName,FDocumentStatus,FForbidStatus"
				isAddFUseOrgId.value = false;
			} else if (type == '物料') {
				popFieldKeys.value = "FNumber,FName,FDocumentStatus,FForbidStatus,FUseOrgId.FNumber,F_BelongCustomer.FNumber"
				filterString.value = [
					Utils.getFilterString('F_BelongCustomer.FNumber', opt.value['客户编码'], '=')
				]
			} else if (type == '批号') {

				popFieldKeys.value = "FLot.FNumber,FExpiryDate,FProduceDate,FBaseQty,FOwnerId.FNumber,FStockOrgId.FName"
				isAddFUseOrgId.value = false
				filterList.value = [{ name: '批号', value: 1, key: 'FLot.FNumber' }]
				filterString.value = [
					Utils.getFilterString('FOwnerId.FNumber', opt.value['客户编码'], '='),
					Utils.getFilterString('FMaterialId.FNumber', list.value[index].FNumber.number, '='),
					Utils.getFilterString('FStockOrgId.FNumber', Utils.getStorage('currentOrganization')?.FNumber, '='),
					Utils.getFilterString('FBaseQty', 0, '>'),
				]
				popType.value = '即时库存'
			} else if (type == '调入仓位') {
				popType.value = '仓库'
				// 设置过滤列表
				filterList.value = [
					{ name: '仓库名称', value: 0, key: "FName" },
					{ name: '仓库编号', value: 1, key: 'FNumber' },
					{ name: '仓位编号', value: 2, key: "FFlexEntryId.FNumber" },
				]
				// 设置获取字段
				popFieldKeys.value = "FNumber,FName,FFlexEntryId.FNumber,FFlexEntryId.FName,FFlexId,FDocumentStatus,FForbidStatus"
			}
			// console.log(type,popFieldKeys.value);

			isShowPop.value = true
		}
	}
	// 辅助资料列表
	const assistantList = ref([] as any)
	const isShowSelectAssistantMethod = ref(false)
	// 选择收费方式
	const selectAssistantMethod = (e : any) => {
		const value = e.detail
		if (popType.value == '计费方式') {
			list.value[currentSelectIndex.value].feeType.value = value.FName;
			list.value[currentSelectIndex.value].feeType.number = value.FNumber;
			return
		}
		list.value[currentSelectIndex.value].feeStandard.value = value.FName;
		list.value[currentSelectIndex.value].feeStandard.number = value.FNumber;

	}
	// 通过分组编号获取辅助资料
	const getAssistantInfo = async (number : string) => {
		if (!number) return;
		const res : any = await getOrderList({
			data: JSON.stringify({
				FormId: Utils.getFormId('辅助资料'),
				FieldKeys: "FNumber,FDataValue,FId.FNumber",
				FilterString: [
					Utils.getFilterString('FId.FNumber', number, '=', '', ''),
					Utils.getFilterString('FDocumentStatus', 'C', '105', '', ''),
					Utils.getFilterString('FForbidStatus', 'A', '105', '', ''),
				],
				OrderString: '',
				assistantList: []
			}),
		})

		assistantList.value = res.map((v : any) => {
			return {
				name: v[1],
				FNumber: v[0],
				FName: v[1]
			}
		});
		isShowSelectAssistantMethod.value = true
	}

	/**
	 * 扫码添加
	 */
	const addByScan = () => {
		Utils.scanCode(async (res : any, code : string) => {
			console.log(code);
			// 判断物料属不属于客户
			const isOk = await JudgingMaterials(code)
			if (!isOk) {
				return Utils.showErr('该物料不属于当前货主！')
			}
			// 获取到物料编码，去查询物料详情并添加数据
			if (code) await getDetailFn(code)
		})
	}
	/**
	 * 判断物料是否属于该客户
	 */
	const JudgingMaterials = async (code : string) => {
		const res : any = await getOrderList({
			data: JSON.stringify({
				FormId: Utils.getFormId("物料"),
				FieldKeys: "FNumber,FName,FDocumentStatus,FForbidStatus,FUseOrgId.FNumber,F_BelongCustomer.FNumber",
				FilterString: [
					Utils.getFilterString('FNumber', code, '=', '', ''),
					Utils.getFilterString('FDocumentStatus', 'C', '105', '', ''),
					Utils.getFilterString('FForbidStatus', 'A', '105', '', ''),
					Utils.getFilterString('FUseOrgId.FNumber', Utils.getStorage('currentOrganization')?.FNumber, '=', '', ''),
					Utils.getFilterString('F_BelongCustomer.FNumber', opt.value['客户编码'], '=')
				],
				OrderString: '',
			}),
		})
		// console.log(res);
		return res && res.length > 0 ? true : false;
	}
	/**
	 * 获取详情
	 */
	const getDetailFn = async (number : string) => {
		const res : any = await getOrderDetailByBillNo({
			FormId: Utils.getFormId('物料'),
			data: JSON.stringify({
				Number: number,
			}),
		});
		// console.log(res, '详情');
		if ((res.Result.ResponseStatus.IsSuccess == true)) {
			const d = res.Result.Result;
			const obj = JSON.parse(JSON.stringify(dataDetail.value));
			obj.FNumber.value = d.Number;
			obj.FNumber.number = d.Number;
			obj.FName.value = d.Name[0]?.Value;
			obj.FName.number = d.Number;
			// 单位
			obj.Unit.value = d.MaterialBase[0]?.BaseUnitId?.Name[0]?.Value;
			obj.Unit.number = d.MaterialBase[0]?.BaseUnitId?.Number
			list.value.push(JSON.parse(JSON.stringify(obj)));
		} else {
			Utils.showErr(res.Result?.ResponseStatus?.Errors[0]?.Message || '查询不到数据，请检查二维码！')
		}
	};

	/**
	 * 添加物料
	 */
	const addMaterial = async () => {
		// list.value.push(JSON.parse(JSON.stringify(dataDetail.value)));
		popType.value = '物料'
		popFieldKeys.value = "FNumber,FName,FDocumentStatus,FForbidStatus,FUseOrgId.FNumber,F_BelongCustomer.FNumber"
		filterString.value = [
			Utils.getFilterString('F_BelongCustomer.FNumber', opt.value['客户编码'], '=')
		]
		filterList.value = []
		isShowPop.value = true;
	};

	/**
	 * 弹窗关闭
	 */
	const close = () => {
		isShowPop.value = false;
	};
	/**
	 * 弹窗确认
	 */
	const popSubmit = async (item : any) => {
		console.log(popType.value, item);
		const type = popType.value
		const d : any = JSON.parse(item.Value)
		switch (type) {
			case '费用项目':
				list.value[currentSelectIndex.value].feeItem.value = item.FName
				list.value[currentSelectIndex.value].feeItem.number = item.FNumber
				break;
			case '物料':
				getDetailFn(item.FNumber)
				break;
			case '即时库存':

				list.value[currentSelectIndex.value].FLot.value = d[0]
				// 生产日期
				list.value[currentSelectIndex.value].FProduceDate.value = d[1] ? Utils.formatDate(new Date(d[2]).getTime()) : ''
				// 有效期至
				list.value[currentSelectIndex.value].FExpiryDate.value = d[2] ? Utils.formatDate(new Date(d[1]).getTime()) : ''
				break;
			case '仓库':

				// 设置仓库
				list.value[currentSelectIndex.value].FDestStockId.value = item.FName
				list.value[currentSelectIndex.value].FDestStockId.number = item.FNumber
				list.value[currentSelectIndex.value].FDestStockLocId.id = d[4]
				list.value[currentSelectIndex.value].FDestStockLocId.number = d[2]
				list.value[currentSelectIndex.value].FDestStockLocId.value = d[3]


		}
		// if (item?.FNumber) {
		// 	await getDetailFn(item.FNumber);
		// 	close();
		// }
	};

	/**
	 * 选择时间 
	 */
	const selectDateTimeFn = (e : any) => {
		if (popType.value == '食用到期日') {
			list.value[currentSelectIndex.value].expiryDate.value = e
		} else if (popType.value == '生产日期') {
			list.value[currentSelectIndex.value].FProduceDate.value = e
		} else if (popType.value == '有效期至') {
			list.value[currentSelectIndex.value].FExpiryDate.value = e
		}




	}
	/**
	 * 删除物料
	 */
	const deleteMaterial = (index : number) => {
		Utils.showModal('是否删除该物料吗？', () => {
			list.value.splice(index, 1);
		});
	};
	const save = () => {
		
		let isOk = true;
		// 提示text
		let tipsText = ''
		// 判断必填项是否填写
		for (let i = 0; i < list.value.length; i++) {
			const v = list.value[i];
			for (const key in v) {
				if (v[key].required === true && (v[key].value === '' || v[key].value === 0)) {
					tipsText = '请输入' + v[key].title;
					isOk = false;
					break; 
				}
				if(opt.value?.parentPage != '出库单' && opt.value?.parentPage != '调拨单' && (v[key].title == '生产日期' || v[key].title == '有效期至') ){
					// 判断日期
					if(new Date(v.FExpiryDate.value) < new Date(v.FProduceDate.value)
					|| new Date(v.expiryDate.value)< new Date(v.FProduceDate.value)
					|| new Date(v.expiryDate.value)> new Date(v.FExpiryDate.value)
					){
						tipsText =new Date(v.FExpiryDate.value) < new Date(v.FProduceDate.value) ? '有效期必须大于生产日期！':
						 new Date(v.expiryDate.value)< new Date(v.FProduceDate.value) ? '食用到期日必须大于生产日期': 
						 '食品到期日不能大于有效期';
						isOk = false;
						break; 
					}
					
				}
			}
			if (!isOk) {
				break; // 中断外层for循环
			}
		}
		if (!isOk) return Utils.showErr(tipsText);
		Utils.setStorage('addMaterial', { warehouse: opt.value, list: list.value });
		uni.navigateBack({
			delta: 1,
		});
	};

	const opt = ref();
	onLoad((options) => {
		// isShowPop.value = true;
		opt.value = options;
		console.log(opt, 'options');
		// if (opt && opt.data) dataDetail.value = JSON.parse(opt.data || '{}');

		if (options?.parentPage == '出库单' || options?.parentPage == '调拨单') {
			for (var key in dataDetail.value) {
				const title = dataDetail.value[key].title
				if (title == '批号' || title == '生产日期' || title == '有效期至') {
					dataDetail.value[key].isShow = true;
					dataDetail.value[key].required = true;
					if(title == '生产日期' || title == '有效期至'){
						dataDetail.value[key].type = 3
						dataDetail.value[key].required = false;
					}
					
				}
				if( options?.parentPage == '调拨单'){
					if(title == '调入仓位' || title == '调入仓库' ){
						dataDetail.value[key].isShow = true;
						dataDetail.value[key].required = true;
					}
				}
			}
		} else {
			for (var key in dataDetail.value) {
				const title = dataDetail.value[key].title
				if (title == '费用项目' || title == '计费标准' || title == '食用到期日'
					|| title == '生产日期' || title == '有效期至') {
					dataDetail.value[key].isShow = true;
					dataDetail.value[key].required = true;
				}


			}
		}
	});
</script>

<style lang="less" scoped>
	.orderDetails {
		padding: 28rpx;
		background: #f6f6f6;
		min-height: 100%;

		>view {
			padding: 28rpx;
			margin-bottom: 20rpx;
			border-radius: 20rpx;
			background-color: #fff;
		}

		.title {
			display: flex;
			align-items: center;
			font-size: 40rpx;
			padding-top: 0;
			margin-bottom: 0;
			background-color: #f6f6f6;
		}

		.orderData {
			.orderDataItem {
				padding: 14rpx 0;
				justify-content: space-between;

				.key {
					font-size: 30rpx;
					white-space: nowrap;
					color: #666;
				}

				.value {
					box-sizing: border-box;
					font-size: 30rpx;
					flex: 1 0 0;
					margin: 0 0 0 20rpx;
					text-align: right;
				}
			}
		}
	}

	.btns {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100vw;
		padding: 28rpx;
		display: flex;
		justify-content: flex-end;
		margin-top: 28rpx;
		z-index: 99;
		background-color: #fff;

		view {
			display: flex;
			align-items: center;
			justify-content: center;
			flex: 1;
			padding: 30rpx;
			margin-right: 20rpx;
			border-radius: 24rpx;
			font-size: 30rpx;
			background-color: #3974f6;
			color: #fff;
		}

		>view:last-child {
			margin-right: 0 !important;
		}

		.pay {
			border: 1px solid #3974f6;
			background-color: transparent;
			color: #3974f6;
		}
	}

	.add {
		position: fixed;
		bottom: 200rpx;
		right: 20rpx;
		width: 100rpx;

		image {
			width: 100rpx;
			height: 100rpx;
		}
	}

	.purse {
		width: 100%;

		.p_item {
			padding: 20rpx 22rpx;
			margin-bottom: 16rpx;
			border-radius: 10rpx;
			background: #f6f6f6;

			font-size: 30rpx;

			.title {
				display: flex;
				align-items: center;
				justify-content: space-between;
				padding: 2rpx 0 24rpx;
				border-bottom: 1px solid #eeeeee;
				font-weight: 500;
				font-size: 34rpx;
				color: #000000;

				.status {
					color: #3974f6;
					font-size: 22rpx;
				}
			}

			.content {
				flex-wrap: wrap;
				padding-top: 20rpx;

				.c_item {
					width: 50%;
					margin-bottom: 26rpx;
					color: #111;
				}
			}

			.btn {
				display: flex;
				justify-content: flex-end;
				padding-top: 12rpx;

				view {
					padding: 12rpx 24rpx;
					border-radius: 10rpx;
					background: #3974f6;
					color: #fff;
				}
			}
		}
	}

	.item {
		padding-bottom: 20rpx;
		font-size: 34rpx;
		color: #333;
		border-bottom: 1px solid #ccc;
		font-weight: 500;
		margin-bottom: 20rpx;
		justify-content: space-between;

		.value {
			color: #3975f6;
		}
	}
</style>